Return the bitwise AND of all numbers in the range¶
Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.
Example 1:
Input: m = 5, n = 7
Output: 4
[1]:
class Solution1(object):
def rangeBitwiseAnd(self, m, n) -> int:
"""
:type m: int
:type n: int
:rtype: int
"""
while m < n:
n &= n - 1
return n
[2]:
s = Solution1()
m = 5
n = 7
assert s.rangeBitwiseAnd(m, n) == 4
[3]:
class Solution2(object):
def rangeBitwiseAnd(self, m, n) -> int:
"""
:type m: int
:type n: int
:rtype: int
"""
i, diff = 0, n - m
while diff:
diff >>= 1
i += 1
return n & m >> i << i
[4]:
s = Solution2()
m = 5
n = 7
assert s.rangeBitwiseAnd(m, n) == 4